package graph;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Graph {
	public ArrayList<Node> nodes = new ArrayList<Node>();
	public ArrayList<Edge> edges = new ArrayList<Edge>();
	public Set<Node> getNodesOfDistance(Node a, int distance) {
		List<Set<Node>> list = nodesOfDistance(a, distance);
		return list.get(list.size()-1);
	}
	public List<Set<Node>> nodesOfDistance(Node a, int distance) {
		ArrayList<Set<Node>> list = new ArrayList<Set<Node>>();
		HashSet<Node> start = new HashSet<Node>();
		start.add(a);
		list.add(start);
		while (list.size()<distance+1) {
			addNeighbour(list);
		}
		return list;
	}
	private void addNeighbour(ArrayList<Set<Node>> list) {
		HashSet<Node> nodes = new HashSet<Node>();
		for (Edge e : edges) {
			if (list.get(list.size()-1).contains(e.a)) {
				if (unknown(e.b, list)) {
					nodes.add(e.b);
				}
			}
			if (list.get(list.size()-1).contains(e.b)) {
				if (unknown(e.a, list)) {
					nodes.add(e.a);
				}
			}
		}
		list.add(nodes);
	}
	private boolean unknown(Node b, ArrayList<Set<Node>> list) {
		for (Set<Node> nodes : list) {
			if (nodes.contains(b)) return false;
		}
		return true;
	}
	@Override
	public String toString() {
		return "Nodes:" + nodes + "\nedges:" + edges + "\n";
	}
	public Set<Node> neighbours(Node node) {
		HashSet<Node> result = new HashSet<Node>();
		for (Edge edge : edges) {
			if (edge.a == node) {
				result.add(edge.b);
			} else if (edge.b == node) {
				result.add(edge.a);
			} 
		}
		return result;
	}
}
